﻿using System;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Interactivity;
using FluentAvalonia.UI.Controls;
using LiftHub.Controls;
using LiftHub.Data.LedgerModels;
using LiftHub.ViewModels.Pages;

namespace LiftHub.Pages;

public partial class LedgerPage : UserControl
{
    public LedgerPage()
    {
        InitializeComponent();
    }
    
    private async void AddClick(object? sender, RoutedEventArgs e)
    {
        if(DataContext is not LedgerPageModel model)return;
        AddLedgerDialog.Content = new AddLedgerControl(model.Categories);
        await AddLedgerDialog.ShowAsync();
    }

    private void ChooseSelectionChange(object? sender, SelectionChangedEventArgs e)
    {
        if((sender as ComboBox)?.SelectedItem is not string choose)return;
        
        if (choose == "从姓名查询")
        {
            NameBox.IsVisible = true;
            CategoriesComboBox.IsVisible = false;
            LeastUpDown.IsVisible = false;
            StartTimePicker.IsVisible = false;
            return;
        }
        
        if (choose == "从金额查询")
        {
            NameBox.IsVisible = false;
            CategoriesComboBox.IsVisible = false;
            LeastUpDown.IsVisible = true;
            StartTimePicker.IsVisible = false;
            return;
        }
        
        if (choose == "从种类查询")
        {
            NameBox.IsVisible = false;
            CategoriesComboBox.IsVisible = true;
            LeastUpDown.IsVisible = false;
            StartTimePicker.IsVisible = false;
            return;
        }
        
        if (choose == "从时间查询")
        {
            NameBox.IsVisible = false;
            CategoriesComboBox.IsVisible = false;
            LeastUpDown.IsVisible = false;
            StartTimePicker.IsVisible = true;
        }
        
    }

    private async void AddCategoryClick(object? sender, RoutedEventArgs e)
    {
        await AddCategoryDialog.ShowAsync();
    }

    private void RemoveClick(object? sender, RoutedEventArgs e)
    {
        if(DataContext is not LedgerPageModel model)return;
        if((sender as Control)?.DataContext is not LedgerModel ledger)return;
        model.Remove(ledger);
    }

    private void LedgerDialogDone(TaskDialogButton sender, EventArgs args)
    {
        if(AddLedgerDialog.Content is not AddLedgerControl view)return;
        var result = view.Done();
        if(result == null)return;
        if(DataContext is not LedgerPageModel model)return;
        model.Add(result);
    }

    private void CategoryDialogDone(TaskDialogButton sender, EventArgs args)
    {
        if(AddCategoryDialog.Content is not AddCategoryControl view)return;
        var result = view.Done();
        if(result == null)return;
        if(DataContext is not LedgerPageModel model)return;
        model.Add(result);
    }
}